/**
 * kl yy-ds @2021
 */
package com.cxps.cloud.utils;

import com.google.common.collect.Queues;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.Queue;

/**
 * 主键生成策略
 *
 * @author YouCai.Liu
 * @since 2021/10/12
 * ...
 */
@Slf4j
public class IdUtils {

    private IdUtils() {}

    private static final int FETCH_SIZE = 500;

    /**
     * 本地主键序列队列
     */
    private static Queue<String> queue;
    static {
        queue = Queues.newConcurrentLinkedQueue();
    }

    private static Sequence sq = new Sequence(0, 0);

    /**
     * 生成唯一ID
     *
     * @return ID
     */
    public static String generateId() {
        if (queue.size() < FETCH_SIZE) {
            synchronized (IdUtils.class) {
                if (queue.size() < FETCH_SIZE) {
                    querySequence();
                }
            }
        }
        return queue.poll();
    }

    private static void querySequence() {
        List<String> list = new ArrayList<>();
        for (int i = 0; i < 1000; i++) {
            list.add(sq.nextId() + "");
        }
        queue.addAll(list);
    }
}
